package storages

import (
	"github.com/pkg/errors"
	"gluenet/internal/glue-srvm/model"
	"gorm.io/gorm"
)

type accountToUserStorage struct{}

var DefaultAccountToUserStorage = &accountToUserStorage{}

func (c *accountToUserStorage) Insert(db *gorm.DB, data model.MeteringAccountToUser) (uint, error) {
	return uint(data.Id), errors.WithStack(db.Create(&data).Error)
}

func (c *accountToUserStorage) Update(db *gorm.DB, filter, data model.MeteringAccountToUser) error {
	return errors.WithStack(db.Model(data).Where(&filter).Updates(&data).Error)
}

func (c *accountToUserStorage) DeleteByID(db *gorm.DB, id uint) error {
	if id == 0 {
		return errors.New("ID cannot be empty.")
	}
	return errors.WithStack(db.Delete(&model.MeteringAccountToUser{Id: uint64(id)}).Error)
}

func (c *accountToUserStorage) FindOne(db *gorm.DB, filter model.MeteringAccountToUser) (*model.MeteringAccountToUser, error) {
	var accountToUser model.MeteringAccountToUser
	err := db.Where(&filter).Find(&accountToUser).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, nil
	}
	return &accountToUser, errors.WithStack(err)
}

func (c *accountToUserStorage) FindAll(db *gorm.DB, filter model.MeteringAccountToUser) ([]model.MeteringAccountToUser, error) {
	var accountToUsers []model.MeteringAccountToUser
	err := db.Where(&filter).Find(&accountToUsers).Error
	if err != nil && err == gorm.ErrRecordNotFound {
		return nil, errors.WithStack(err)
	}
	return accountToUsers, nil
}
